<template>
    <div style="height: 100%">
        <transition :name="togglePageAnimationName">
            <keep-alive :include="keepActivePageName">
                <router-view />
            </keep-alive>
        </transition>

        <yd-popup v-model="offline" position="center" width="70%" :close-on-masker="false" masker-opacity=".7">
            <div class="offLine">{{ $t('message.offLine') }}！</div>
            <div class="offLine-btn" @click="offLineEvent">{{ $t('message.knowThat') }}</div>
        </yd-popup>
    </div>
</template>

<script>
export default {
  name: "App",
  created() {
    let ws = null;

    if (process.env.NODE_ENV == "development") {
      ws = new ReconnectingWebSocket(
        `ws://${process.env.webcoketUrl}/websocket`
      );
    } else {
      ws = new ReconnectingWebSocket(
        `wss://${process.env.webcoketUrl}/websocket`
      );
    }

    let token = this.$storage.get("token");
    let userId = this.$storage.get("userInfo").id;
    ws.onopen = () =>
      ws.send(JSON.stringify({ room: `${userId}:${token}`, action: "join" }));
    ws.onmessage = (event) => {
      let { action } = JSON.parse(event.data);
      if (action == "offline") this.offline = true;
    };
    // 断开 web socket 连接成功触发事件
    ws.onclose = (e) => console.log(e);
  },
  data() {
    return {
      keepActivePageName: ["index", "userInfo"],
      togglePageAnimationName: "",
      offline: false,
    };
  },
  watch: {
    $route: function(to, from) {
      if (from.name === "index" && to.name === "userInfo") {
        this.togglePageAnimationName = "addPage";
      } else if (from.name === "userInfo" && to.name === "index") {
        this.togglePageAnimationName = "backPage";
      } else {
        this.togglePageAnimationName = "noAnimation";
      }
    },
  },
  methods: {
    offLineEvent() {
      this.$storage.remove("token");
      this.$storage.remove("userInfo");
      this.offline = false;
      if (this.$route.name != "login") this.$router.push({ name: "login" });
    },
  },
};
</script>

<style lang="scss">
@import "./assets/scss/main";
</style>
